<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>仪表盘 - 资产管理系统</title>
    <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="/xlsx/xlsx.core.min.js"></script>
    <style>
        :root {
            --primary-color: #4e73df;
            --secondary-color: #f8f9fa;
            --dark-color: #343a40;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --info-color: #17a2b8;
            --light-color: #f8f9fa;
            --muted-color: #6c757d;
        }
    
        body {
            background-color: #f8f9fc;
            font-family: 'Inter', system-ui, sans-serif;
            font-size: 14px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
    
        /* 导航栏保持全宽 */
        .navbar {
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            padding: 0.5rem 0;
            background-color: var(--primary-color);
            transition: background-color 0.3s ease;
            width: 100%;
        }
    
        .navbar:hover {
            background-color: #4367d6;
        }
    
        .navbar-brand {
            font-weight: 600;
            font-size: 1.35rem;
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
    
        /* 主要内容区域调整为85%宽度 */
        .container {
            width: 85%;
            max-width: 85%;
            padding-bottom: 1.5rem;
            flex: 1;
            margin: 0 auto;
        }
    
        .search-panel {
            background: white;
            padding: 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
            margin-bottom: 1.5rem;
            border: 1px solid #e3e6f0;
        }
    
        .table-responsive {
            border-radius: 0.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
            background: white;
            overflow-x: auto;
            border: 1px solid #e3e6f0;
        }
    
        .table {
            width: 100%;
            table-layout: auto;
            margin-bottom: 0;
            font-size: 13px;
            color: #5a5c69;
        }
    
        .table-dark {
            background-color: var(--primary-color) !important;
            font-size: 13px;
            color: white;
        }
    
        .table th,
        .table td {
    white-space: normal;
    word-wrap: break-word;
}
    
        /* 为特定列设置固定宽度 */
.table td:nth-child(12) {
    max-width: 200px;
    min-width: 100px;
}
        .table td:not(:nth-child(12)):not(:nth-child(13)) {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    
        .table-hover tbody tr:hover {
            background-color: rgba(78, 115, 223, 0.05);
        }
    
        .asset-image {
            height: 80px;
            width: auto;
            object-fit: contain;
            margin: 3px;
            border: 1px solid #eee;
            border-radius: 3px;
            transition: transform 0.3s;
        }
    
        .asset-image:hover {
            transform: scale(1.05);
        }
    
        .image-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-start;
            gap: 5px;
        }
    
        .btn-outline-light {
            border-color: rgba(255, 255, 255, 0.3);
            padding: 5px 10px;
            font-size: 13px;
        }
    
        .action-btn {
            white-space: nowrap;
            padding: 5px 10px;
            font-size: 12px;
            margin: 2px;
            border-radius: 0.25rem;
            transition: all 0.2s ease;
        }
    
        .action-btn:hover {
            transform: translateY(-1px);
        }
    
        .modal-header {
            background-color: var(--primary-color);
            color: white;
            padding: 1rem;
            border-radius: 0.35rem 0.35rem 0 0;
        }
    
        .modal-title {
            font-size: 1.1rem;
            font-weight: 600;
        }
    
        .modal-body,
        .modal-footer {
            padding: 1rem;
        }
    
        .form-label {
            font-weight: 500;
            margin-bottom: 0.3rem;
            font-size: 13px;
            color: #5a5c69;
        }
    
        .form-control-sm,
        .form-select-sm {
            font-size: 13px;
            padding: 0.375rem 0.75rem;
            border: 1px solid #d1d3e2;
            border-radius: 0.35rem;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
    
        .form-control-sm:focus,
        .form-select-sm:focus {
            border-color: #bac8f3;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
        }
    
        .loading-spinner {
            display: inline-block;
            width: 1rem;
            height: 1rem;
            border: 2px solid rgba(0, 0, 0, .1);
            border-radius: 50%;
            border-top-color: var(--primary-color);
            animation: spin 1s ease-in-out infinite;
        }
    
        .status-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 12px;
            font-weight: 500;
            display: inline-block;
        }
    
        .status-normal {
            background-color: var(--success-color);
            color: white;
        }
    
        .status-repairing {
            background-color: var(--warning-color);
            color: #212529;
        }
    
        .status-scrapped {
            background-color: var(--danger-color);
            color: white;
        }
    
        .status-idle {
            background-color: var(--muted-color);
            color: white;
        }
    
        .pagination {
            display: flex;
            gap: 0.25rem;
        }
    
        .page-item {
            margin: 0;
        }
    
        .page-link {
            padding: 0.375rem 0.75rem;
            border: 1px solid #d1d3e2;
            color: var(--primary-color);
            border-radius: 0.35rem;
            transition: all 0.2s ease;
        }
    
        .page-link:hover {
            background-color: #eaecf4;
            border-color: #d1d3e2;
        }
    
        .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
        }
    
        .page-item.disabled .page-link {
            color: #b7b9cc;
            pointer-events: none;
            background-color: #f8f9fc;
            border-color: #d1d3e2;
        }
    
        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
    
        /* 卡片样式 */
        .card {
            background: white;
            border-radius: 0.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
            border: 1px solid #e3e6f0;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
    
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1.5rem 0 rgba(58, 59, 69, 0.2);
        }
    
        .card-body {
            padding: 1.5rem;
        }
    
        /* 按钮动画效果 */
        .btn-animated {
            position: relative;
            overflow: hidden;
        }
    
        .btn-animated:after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 5px;
            height: 5px;
            background: rgba(255, 255, 255, 0.3);
            opacity: 0;
            border-radius: 100%;
            transform: scale(1, 1) translate(-50%);
            transform-origin: 50% 50%;
        }
    
        .btn-animated:active:after {
            animation: ripple 0.6s ease-out;
        }
    
        @keyframes ripple {
            0% {
                transform: scale(0, 0);
                opacity: 0.5;
            }
            100% {
                transform: scale(20, 20);
                opacity: 0;
            }
        }
    
        /* 页脚保持全宽 */
        footer {
            background-color: white;
            border-top: 1px solid #e3e6f0;
            padding: 1rem 0;
            margin-top: auto;
            width: 100%;
        }
    
        .footer-links {
            display: flex;
            gap: 1rem;
        }
    
        .footer-links a {
            color: var(--muted-color);
            transition: color 0.2s ease;
        }
    
        .footer-links a:hover {
            color: var(--primary-color);
            text-decoration: none;
        }
    
        /* 响应式调整 */
        @media (max-width: 1200px) {
            .container {
                width: 90%;
                max-width: 90%;
            }
        }
    
        @media (max-width: 768px) {
            .container {
                width: 95%;
                max-width: 95%;
                padding-left: 15px;
                padding-right: 15px;
            }
    
            .table-responsive {
                border-radius: 0;
            }
    
            .table th,
            .table td {
                padding: 0.5rem;
                white-space: normal !important;
            }
    
            .action-btn {
                padding: 0.25rem 0.5rem;
                font-size: 11px;
            }
    
            .search-panel {
                padding: 1rem;
            }
        }
    
        @media (max-width: 576px) {
            .container {
                width: 100%;
                max-width: 100%;
            }
        }
    
        /* 导航栏补充样式 */
        .nav-link {
            position: relative;
            overflow: hidden;
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            transition: all 0.2s ease;
        }
    
        .nav-link:not(.active):after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 0;
            height: 2px;
            background-color: white;
            transition: width 0.3s ease;
            border-radius: 2px;
        }
    
        .nav-link:not(.active):hover:after {
            width: 100%;
        }
    
        .nav-link.active {
            background-color: rgba(255, 255, 255, 0.1);
        }
    
        .navbar-brand svg {
            transition: transform 0.3s ease;
        }
    
        .navbar-brand:hover svg {
            transform: scale(1.1);
        }
    
        .btn-outline-light {
            border-width: 1.5px;
        }
    
        /* 适配深色模式的过渡效果 */
        @media (prefers-color-scheme: dark) {
            .navbar {
                background-color: #3a5bc9;
            }
    
            .navbar:hover {
                background-color: #324dab;
            }
        }
    </style>
</head>

<body>

    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container py-2">
            <!-- 品牌标识 -->
            <a class="navbar-brand" href="#">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M4 6H20V20H4V6Z" stroke="white" stroke-width="2" stroke-linecap="round"
                        stroke-linejoin="round" />
                    <path d="M4 10H20" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    <path d="M8 6V2" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    <path d="M16 6V2" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                </svg>
                资产管理系统
            </a>

            <!-- 移动端菜单按钮 -->
            <button class="navbar-toggler py-1" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                style="border-color: rgba(255,255,255,0.3);">
                <span class="navbar-toggler-icon"></span>
            </button>

            <!-- 菜单内容 -->
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto align-items-center gap-1">
                    <li class="nav-item">
                        <a class="nav-link active" href="/dashboard">
                            <i class="fa fa-dashboard mr-1"></i> 首页
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/report">
                            <i class="fa fa-plus-circle mr-1"></i> 资产上报
                        </a>
                    </li>
                    <li id="adminLink" class="nav-item" style="display: none;">
                        <a class="nav-link" href="/admin/users">
                            <i class="fa fa-users mr-1"></i> 用户管理
                        </a>
                    </li>
                </ul>

                <div class="d-flex align-items-center">
                    <button id="themeToggle" class="btn btn-outline-light btn-sm rounded-circle me-2">
                        <i class="fa fa-moon-o"></i>
                    </button>
                    <a href="/logout"
                        class="btn btn-outline-light btn-sm rounded-pill px-4 py-1.5">
                        <i class="fa fa-sign-out mr-1"></i> 退出
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container mt-3">
        
        <!-- <div class="row g-4 mb-4">
            <div class="col-md-6 col-lg-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <p class="text-sm text-muted mb-1">总资产</p>
                                <h3 class="mb-0" id="totalAssets">0</h3>
                                <p class="text-sm text-success mt-2">
                                    <i class="fa fa-arrow-up"></i> 12.5% <span class="text-muted">较上月</span>
                                </p>
                            </div>
                            <div class="bg-primary bg-opacity-10 p-3 rounded">
                                <i class="fa fa-cubes text-primary"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-lg-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <p class="text-sm text-muted mb-1">在用资产</p>
                                <h3 class="mb-0" id="activeAssets">0</h3>
                                <p class="text-sm text-success mt-2">
                                    <i class="fa fa-arrow-up"></i> 8.2% <span class="text-muted">较上月</span>
                                </p>
                            </div>
                            <div class="bg-success bg-opacity-10 p-3 rounded">
                                <i class="fa fa-check-circle text-success"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-lg-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <p class="text-sm text-muted mb-1">维修中</p>
                                <h3 class="mb-0" id="repairingAssets">0</h3>
                                <p class="text-sm text-warning mt-2">
                                    <i class="fa fa-arrow-up"></i> 3.1% <span class="text-muted">较上月</span>
                                </p>
                            </div>
                            <div class="bg-warning bg-opacity-10 p-3 rounded">
                                <i class="fa fa-wrench text-warning"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-lg-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <p class="text-sm text-muted mb-1">总价值(元)</p>
                                <h3 class="mb-0" id="totalValue">0</h3>
                                <p class="text-sm text-success mt-2">
                                    <i class="fa fa-arrow-up"></i> 15.3% <span class="text-muted">较上月</span>
                                </p>
                            </div>
                            <div class="bg-info bg-opacity-10 p-3 rounded">
                                <i class="fa fa-rmb text-info"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div> -->

        <!-- 图表区域 -->
        <!-- <div class="row g-4 mb-4">
            <div class="col-lg-8">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h5 class="card-title mb-0">资产趋势</h5>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-primary btn-sm">月</button>
                                <button class="btn btn-outline-secondary btn-sm">季</button>
                                <button class="btn btn-outline-secondary btn-sm">年</button>
                            </div>
                        </div>
                        <div style="height: 300px;">
                           
                            <div class="d-flex justify-content-center align-items-center h-100 text-muted">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h5 class="card-title mb-0">资产分类</h5>
                            <button class="btn btn-link text-muted p-0">
                                <i class="fa fa-ellipsis-v"></i>
                            </button>
                        </div>
                        <div style="height: 300px;">
                          
                            <div class="d-flex justify-content-center align-items-center h-100 text-muted">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div> -->

        <div class="search-panel">
            <!-- <h5 class="mb-3">资产搜索</h5> -->
            <form id="searchForm">
                <div class="row g-2 align-items-center">
                    <div class="col-md-2">
                        <label for="startDate" class="form-label">开始日期</label>
                        <input type="date" class="form-control form-control-sm" id="startDate">
                    </div>
                    <div class="col-md-2">
                        <label for="endDate" class="form-label">结束日期</label>
                        <input type="date" class="form-control form-control-sm" id="endDate">
                    </div>
                    <div class="col-md-2">
                        <label for="statusFilter" class="form-label">资产状态</label>
                        <select class="form-select form-control-sm" id="statusFilter">
                            <option value="全部">全部</option>
                            <option value="正常">正常</option>
                            <option value="维修中">维修中</option>
                            <option value="报废">报废</option>
                            <option value="闲置">闲置</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="departmentFilter" class="form-label">所属部门</label>
                        <input type="text" class="form-control form-control-sm" id="departmentFilter">
                    </div>
                    <div class="col-md-3">
                        <div class="d-flex flex-column gap-2">
                            <button id="exportExcelBtn" class="btn btn-success btn-sm btn-animated">
                                <i class="fa fa-download me-2"></i>导出Excel
                            </button>
                            <button type="submit" class="btn btn-primary btn-sm btn-animated">
                                <i class="fa fa-search me-2"></i>查询
                            </button>
                            
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="card">
            <!-- <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">资产列表</h5>
                <button id="addAssetBtn" class="btn btn-primary btn-sm btn-animated">
                    <i class="fa fa-plus mr-2"></i>新增资产
                </button>
            </div> -->
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th>ID</th>
                            <th>编号</th>
                            <th>名称</th>
                            <th>大类</th>
                            <th>小类</th>
                            <th>-</th>
                            <th>价值</th>
                            <th>状态</th>
                            <th>部门</th>
                            <th>存放位置</th>
                            <th>购买日期</th>
                            <th>详细描述</th>
                            <th>图片</th>
                            <th>-</th>
                            <th>上报时间</th>
                            <th id="actionColumn" style="display: none;">操作</th>
                        </tr>
                    </thead>
                    <tbody id="reportsTable">
                        <tr>
                            <td colspan="15" class="text-center py-3">
                                <div class="loading-spinner"></div>
                                <span class="ms-2">加载中...</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="card-footer d-flex flex-column flex-md-row justify-content-between align-items-center">
                <div class="text-sm text-muted mb-2 mb-md-0">
                    显示 <span id="currentRange">0-0</span> 条，共 <span id="totalItems">0</span> 条记录
                </div>
                <nav>
                    <ul class="pagination pagination-sm mb-0">
                        <li class="page-item" id="prevPageBtn">
                            <a class="page-link" href="#" aria-label="上一页">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                        <div id="paginationNumbers" class="d-flex"></div>
                        <li class="page-item" id="nextPageBtn">
                            <a class="page-link" href="#" aria-label="下一页">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>

    <footer class="mt-auto py-3">
        <div class="container">
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-center">
                <p class="text-sm text-muted mb-2 mb-md-0">© 2025 资产管理系统. TIMI开发.</p>
                <div class="footer-links">
                    <a href="#" class="text-muted">
                        <i class="fa fa-question-circle mr-1"></i> 帮助中心
                    </a>
                    <a href="#" class="text-muted">
                        <i class="fa fa-file-text-o mr-1"></i> 使用手册
                    </a>
                    <a href="#" class="text-muted">
                        <i class="fa fa-envelope-o mr-1"></i> 联系我们
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteReportModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除资产记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-4">
                        <div class="d-inline-flex align-items-center justify-content-center w-16 h-16 rounded-circle bg-danger bg-opacity-10 mb-3">
                            <i class="fa fa-exclamation-triangle text-danger fs-4"></i>
                        </div>
                        <p>确定要删除这条资产记录吗？</p>
                        <p class="text-danger"><strong>警告：</strong>此操作将永久删除记录及相关图片，无法恢复！</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger btn-animated" id="confirmDeleteReport">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑资产模态框 -->
    <div class="modal fade" id="editReportModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h5 class="modal-title">编辑资产记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-3">
                    <form id="editReportForm">
                        <input type="hidden" id="editReportId">
                        <div class="row g-2">
                            <div class="col-md-6">
                                <label for="editAssetNumber" class="form-label mb-1">资产编号</label>
                                <input type="text" class="form-control form-control-sm" id="editAssetNumber" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editAssetName" class="form-label mb-1">资产名称*</label>
                                <input type="text" class="form-control form-control-sm" id="editAssetName" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editCategoryMain" class="form-label mb-1">大类*</label>
                                <select class="form-select form-select-sm" id="editCategoryMain" required>
                                    <!-- 动态加载 -->
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="editCategorySub" class="form-label mb-1">小类</label>
                                <input type="text" class="form-control form-control-sm" id="editCategorySub">
                            </div>
                            <div class="col-md-4">
                                <label for="editUnit" class="form-label mb-1">单位*</label>
                                <select class="form-select form-select-sm" id="editUnit" required>
                                    <!-- 动态加载 -->
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="editValue" class="form-label mb-1">价值*</label>
                                <input type="number" class="form-control form-control-sm" id="editValue" min="0"
                                    step="0.01" required>
                            </div>
                            <div class="col-md-4">
                                <label for="editStatus" class="form-label mb-1">状态*</label>
                                <select class="form-select form-select-sm" id="editStatus" required>

                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="editDepartment" class="form-label mb-1">所属部门*</label>
                                <input type="text" class="form-control form-control-sm" id="editDepartment" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editLocation" class="form-label mb-1">存放位置*</label>
                                <input type="text" class="form-control form-control-sm" id="editLocation" required>
                            </div>
                            <div class="col-md-4">
                                <label for="editServiceLife" class="form-label mb-1">使用年限(年)</label>
                                <input type="number" class="form-control form-control-sm" id="editServiceLife" min="1">
                            </div>
                            <div class="col-md-4">
                                <label for="editDepreciationRate" class="form-label mb-1">折旧率(%)</label>
                                <input type="number" class="form-control form-control-sm" id="editDepreciationRate"
                                    min="0" max="100" step="0.1">
                            </div>
                            <div class="col-md-4">
                                <label for="editPurchaseDate" class="form-label mb-1">购买日期</label>
                                <input type="date" class="form-control form-control-sm" id="editPurchaseDate">
                            </div>
                            <div class="col-md-6">
                                <label for="editManufacturer" class="form-label mb-1">生产厂商</label>
                                <input type="text" class="form-control form-control-sm" id="editManufacturer">
                            </div>
                            <div class="col-md-6">
                                <label for="editModel" class="form-label mb-1">型号</label>
                                <input type="text" class="form-control form-control-sm" id="editModel">
                            </div>
                            <div class="col-12">
                                <label for="editDescription" class="form-label mb-1">详细描述</label>
                                <textarea class="form-control form-control-sm" id="editDescription" rows="2"></textarea>
                            </div>
                            <!-- 修改编辑模态框中的图片上传区域 -->
                            <div class="col-12 mt-2">
                                <label class="form-label mb-1">图片</label>
                                <!-- 现有图片预览区 -->
                                <div id="editImagePreview" class="image-container mb-2 d-flex flex-wrap gap-2"></div>

                                <!-- 隐藏字段存储现有图片信息 -->
                                <input type="hidden" id="existingImages">

                                <div class="mb-2">
                                    <label for="editImages" class="form-label mb-1">上传新图片 (最多3张)</label>
                                    <input type="file" class="form-control form-control-sm" id="editImages"
                                        name="images" multiple accept="image/*">
                                    <div class="form-text">支持JPEG、PNG格式，每张图片不超过1MB</div>
                                </div>

                                <!-- 新上传图片预览区（横向排列） -->
                                <div id="imagePreviewContainer" class="d-flex flex-wrap gap-2 mb-2"></div>

                                <div class="alert alert-info py-1 px-2 mb-2">
                                    <small>提示：新上传的图片将添加到现有图片中，点击图片上的X可删除</small>
                                </div>
                            </div>
                    </form>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary btn-sm btn-animated" id="saveEditReport">保存修改</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加资产模态框 -->
    <div class="modal fade" id="addReportModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h5 class="modal-title">新增资产记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-3">
                    <form id="addReportForm">
                        <div class="row g-2">
                            <div class="col-md-6">
                                <label for="addAssetNumber" class="form-label mb-1">资产编号</label>
                                <input type="text" class="form-control form-control-sm" id="addAssetNumber" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addAssetName" class="form-label mb-1">资产名称*</label>
                                <input type="text" class="form-control form-control-sm" id="addAssetName" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addCategoryMain" class="form-label mb-1">大类*</label>
                                <select class="form-select form-select-sm" id="addCategoryMain" required>
                                    <!-- 动态加载 -->
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="addCategorySub" class="form-label mb-1">小类</label>
                                <input type="text" class="form-control form-control-sm" id="addCategorySub">
                            </div>
                            <div class="col-md-4">
                                <label for="addUnit" class="form-label mb-1">单位*</label>
                                <select class="form-select form-select-sm" id="addUnit" required>
                                    <!-- 动态加载 -->
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="addValue" class="form-label mb-1">价值*</label>
                                <input type="number" class="form-control form-control-sm" id="addValue" min="0"
                                    step="0.01" required>
                            </div>
                            <div class="col-md-4">
                                <label for="addStatus" class="form-label mb-1">状态*</label>
                                <select class="form-select form-select-sm" id="addStatus" required>
                                    <!-- 动态加载 -->
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="addDepartment" class="form-label mb-1">所属部门*</label>
                                <input type="text" class="form-control form-control-sm" id="addDepartment" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addLocation" class="form-label mb-1">存放位置*</label>
                                <input type="text" class="form-control form-control-sm" id="addLocation" required>
                            </div>
                            <div class="col-md-4">
                                <label for="addServiceLife" class="form-label mb-1">使用年限(年)</label>
                                <input type="number" class="form-control form-control-sm" id="addServiceLife" min="1">
                            </div>
                            <div class="col-md-4">
                                <label for="addDepreciationRate" class="form-label mb-1">折旧率(%)</label>
                                <input type="number" class="form-control form-control-sm" id="addDepreciationRate"
                                    min="0" max="100" step="0.1">
                            </div>
                            <div class="col-md-4">
                                <label for="addPurchaseDate" class="form-label mb-1">购买日期</label>
                                <input type="date" class="form-control form-control-sm" id="addPurchaseDate">
                            </div>
                            <div class="col-md-6">
                                <label for="addManufacturer" class="form-label mb-1">生产厂商</label>
                                <input type="text" class="form-control form-control-sm" id="addManufacturer">
                            </div>
                            <div class="col-md-6">
                                <label for="addModel" class="form-label mb-1">型号</label>
                                <input type="text" class="form-control form-control-sm" id="addModel">
                            </div>
                            <div class="col-12">
                                <label for="addDescription" class="form-label mb-1">详细描述</label>
                                <textarea class="form-control form-control-sm" id="addDescription" rows="2"></textarea>
                            </div>
                            <div class="col-12 mt-2">
                                <label class="form-label mb-1">图片</label>
                                <div id="addImagePreview" class="image-container mb-2 d-flex flex-wrap gap-2"></div>
                                <div class="mb-2">
                                    <label for="addImages" class="form-label mb-1">上传图片 (最多3张)</label>
                                    <input type="file" class="form-control form-control-sm" id="addImages"
                                        name="images" multiple accept="image/*">
                                    <div class="form-text">支持JPEG、PNG格式，每张图片不超过1MB</div>
                                </div>
                                <div id="addImagePreviewContainer" class="d-flex flex-wrap gap-2 mb-2"></div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary btn-sm btn-animated" id="saveAddReport">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查看图片模态框 -->
    <div class="modal fade" id="viewImageModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content bg-transparent border-0">
                <button type="button" class="btn-close btn-close-white position-absolute top-0 end-0 m-3" data-bs-dismiss="modal" aria-label="Close"></button>
                <div class="modal-body p-0 text-center">
                    <img id="viewImage" src="" alt="资产图片" class="img-fluid rounded" style="max-height: 80vh;">
                </div>
            </div>
        </div>
    </div>

    <script src="/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- 原始脚本保持不变 -->
    <script>
        let currentDeleteReportId = null;
        let currentEditReportId = null;
        let isAdmin = false;
        let deleteReportModal = null;
        let editReportModal = null;
        let addReportModal = null;
        let viewImageModal = null;
    
        // 分页相关变量
        let currentPage = 1;
        const pageSize = 10;
        let totalItems = 0;
        let totalPages = 0;
    
        document.addEventListener('DOMContentLoaded', function () {
            deleteReportModal = new bootstrap.Modal(document.getElementById('deleteReportModal'));
            editReportModal = new bootstrap.Modal(document.getElementById('editReportModal'));
            addReportModal = new bootstrap.Modal(document.getElementById('addReportModal'));
            viewImageModal = new bootstrap.Modal(document.getElementById('viewImageModal'));
    
            const today = new Date();
            const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    
            document.getElementById('startDate').valueAsDate = firstDayOfMonth;
            document.getElementById('endDate').valueAsDate = today;
    
            initializePage();
    
            document.getElementById('searchForm').addEventListener('submit', function (e) {
                e.preventDefault();
                currentPage = 1; // 搜索时重置到第一页
                loadReports();
            });
    
            document.getElementById('exportExcelBtn').addEventListener('click', exportToExcel);
    
            // 分页按钮事件
            document.getElementById('prevPageBtn').addEventListener('click', function (e) {
                e.preventDefault();
                if (currentPage > 1) {
                    currentPage--;
                    loadReports();
                }
            });
    
            document.getElementById('nextPageBtn').addEventListener('click', function (e) {
                e.preventDefault();
                if (currentPage < totalPages) {
                    currentPage++;
                    loadReports();
                }
            });
    
            // 新增资产按钮
            document.getElementById('addAssetBtn').addEventListener('click', function() {
                addReportModal.show();
            });
    
            // 主题切换
            document.getElementById('themeToggle').addEventListener('click', function() {
                document.body.classList.toggle('dark');
                const icon = this.querySelector('i');
                if (icon.classList.contains('fa-moon-o')) {
                    icon.classList.remove('fa-moon-o');
                    icon.classList.add('fa-sun-o');
                } else {
                    icon.classList.remove('fa-sun-o');
                    icon.classList.add('fa-moon-o');
                }
            });
        });
    
        async function initializePage() {
            try {
                isAdmin = await checkAdmin();
    
                if (isAdmin) {
                    document.getElementById('adminLink').style.display = 'block';
                    document.getElementById('actionColumn').style.display = 'table-cell';
                }
    
                await loadConfig();
                await loadReports();
            } catch (error) {
                console.error('初始化失败:', error);
                showError('页面初始化失败: ' + error.message);
            }
        }
    
        async function loadConfig() {
            try {
                const response = await fetch('/config.json');
                if (!response.ok) throw new Error('加载配置失败');
                const config = await response.json();
    
                updateStatusDropdown(config.statuses);
                updateCategoryDropdown(config.categories);
                updateUnitDropdown(config.units);
            } catch (error) {
                console.error('加载配置失败:', error);
            }
        }
    
        function updateCategoryDropdown(categories) {
            const categoryMain = document.getElementById('editCategoryMain');
            const addCategoryMain = document.getElementById('addCategoryMain');
            categoryMain.innerHTML = '';
            addCategoryMain.innerHTML = '';
            categories.forEach(category => {
                categoryMain.innerHTML += `<option value="${category}">${category}</option>`;
                addCategoryMain.innerHTML += `<option value="${category}">${category}</option>`;
            });
        }
    
        function updateUnitDropdown(units) {
            const unitInput = document.getElementById('editUnit');
            const addUnitInput = document.getElementById('addUnit');
            unitInput.innerHTML = '';
            addUnitInput.innerHTML = '';
            units.forEach(unit => {
                unitInput.innerHTML += `<option value="${unit}">${unit}</option>`;
                addUnitInput.innerHTML += `<option value="${unit}">${unit}</option>`;
            });
        }
    
        function updateStatusDropdown(statuses) {
            const statusFilter = document.getElementById('statusFilter');
            const editStatus = document.getElementById('editStatus');
            const addStatus = document.getElementById('addStatus');
            
            statusFilter.innerHTML = '<option value="全部">全部</option>';
            editStatus.innerHTML = '';
            addStatus.innerHTML = '';
            
            statuses.forEach(status => {
                statusFilter.innerHTML += `<option value="${status}">${status}</option>`;
                editStatus.innerHTML += `<option value="${status}">${status}</option>`;
                addStatus.innerHTML += `<option value="${status}">${status}</option>`;
            });
        }
    
        async function checkAdmin() {
            try {
                const response = await fetch('/api/users');
                return response.ok;
            } catch (error) {
                console.error('权限检查失败:', error);
                return false;
            }
        }
    
        async function loadReports() {
            try {
                const startDate = document.getElementById('startDate').value;
                const endDate = document.getElementById('endDate').value;
                const status = document.getElementById('statusFilter').value;
                const department = document.getElementById('departmentFilter').value.trim();
    
                let url = `/api/reports?page=${currentPage}&pageSize=${pageSize}`;
                if (startDate) url += `&start_date=${encodeURIComponent(startDate)}`;
                if (endDate) url += `&end_date=${encodeURIComponent(endDate)}`;
                if (status !== '全部') url += `&status=${encodeURIComponent(status)}`;
                if (department) url += `&department=${encodeURIComponent(department)}`;
    
                const tableBody = document.getElementById('reportsTable');
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="16" class="text-center py-3">
                            <div class="loading-spinner"></div>
                            <span class="ms-2">加载中...</span>
                        </td>
                    </tr>
                `;
    
                const response = await fetch(url);
                if (!response.ok) throw new Error(`获取数据失败: ${response.status}`);
    
                const data = await response.json();
                
                // 更新分页信息
                totalItems = data.pagination?.total || 0;
                totalPages = data.pagination?.totalPages || 1;
                currentPage = data.pagination?.currentPage || 1;
                const reports = data.data || [];
    
                updatePaginationInfo();
                renderReports(reports);
                renderPaginationControls();
    
            } catch (error) {
                console.error('加载报告数据失败:', error);
                const tableBody = document.getElementById('reportsTable');
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="16" class="text-center text-danger py-3">
                            ${error.message || '加载数据失败'}
                        </td>
                    </tr>
                `;
    
                totalItems = 0;
                currentPage = 1;
                updatePaginationInfo();
                document.getElementById('prevPageBtn').classList.add('disabled');
                document.getElementById('nextPageBtn').classList.add('disabled');
                document.getElementById('paginationNumbers').innerHTML = '';
            }
        }
    
        function updatePaginationInfo() {
            const startItem = totalItems > 0 ? (currentPage - 1) * pageSize + 1 : 0;
            const endItem = totalItems > 0 ? Math.min(currentPage * pageSize, totalItems) : 0;
    
            document.getElementById('currentRange').textContent = `${startItem}-${endItem}`;
            document.getElementById('totalItems').textContent = totalItems;
        }
    
        function renderPaginationControls() {
            const paginationNumbers = document.getElementById('paginationNumbers');
            paginationNumbers.innerHTML = '';
    
            if (totalPages <= 1) {
                document.getElementById('prevPageBtn').classList.add('disabled');
                document.getElementById('nextPageBtn').classList.add('disabled');
                return;
            }
    
            document.getElementById('prevPageBtn').classList.toggle('disabled', currentPage === 1);
    
            let startPage = Math.max(1, currentPage - 3);
            let endPage = Math.min(startPage + 6, totalPages);
    
            if (endPage - startPage < 6 && startPage > 1) {
                startPage = Math.max(1, endPage - 6);
            }
    
            for (let i = startPage; i <= endPage; i++) {
                const pageItem = document.createElement('li');
                pageItem.className = `page-item ${i === currentPage ? 'active' : ''}`;
                pageItem.innerHTML = `<a class="page-link" href="#">${i}</a>`;
    
                pageItem.querySelector('a').addEventListener('click', (e) => {
                    e.preventDefault();
                    if (i !== currentPage) {
                        currentPage = i;
                        loadReports();
                    }
                });
    
                paginationNumbers.appendChild(pageItem);
            }
    
            document.getElementById('nextPageBtn').classList.toggle('disabled', currentPage === totalPages);
        }
    
        function renderReports(reports) {
            const tableBody = document.getElementById('reportsTable');
    
            if (!Array.isArray(reports)) {
                console.error('预期接收数组，但收到:', reports);
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="16" class="text-center text-danger py-3">
                            加载数据失败：数据格式不正确
                        </td>
                    </tr>
                `;
                return;
            }
    
            if (reports.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="16" class="text-center text-muted py-3">
                            <i class="fa fa-search-minus me-2"></i>没有找到符合条件的记录
                        </td>
                    </tr>
                `;
                return;
            }
    
            let html = '';
    
            reports.forEach(report => {
                let imagesHtml = '<div class="image-container">';
                if (report.images && report.images.length > 0) {
                    report.images.forEach(img => {
                        imagesHtml += `
                            <a href="${img}" target="_blank">
                                <img src="${img}" class="asset-image" alt="资产图片">
                            </a>
                        `;
                    });
                } else {
                    imagesHtml += '<span class="text-muted">无图片</span>';
                }
                imagesHtml += '</div>';
    
                const statusClass =
                    report.status === '正常' ? 'status-normal' :
                        report.status === '维修中' ? 'status-repairing' :
                            report.status === '报废' ? 'status-scrapped' : 'status-idle';
    
                const actionCell = isAdmin ?
                    `<td class="action-buttons">
                        <button class="btn btn-sm btn-primary action-btn edit-report-btn" data-id="${report.id}">
                            <i class="fa fa-pencil me-1"></i>改
                        </button>
                        <button class="btn btn-sm btn-danger action-btn delete-report-btn" data-id="${report.id}">
                            <i class="fa fa-trash me-1"></i>删
                        </button>
						 <button class="btn btn-sm btn-info action-btn duplicate-report-btn" data-id="${report.id}">
            <i class="fa fa-copy me-1"></i>复制新增
        </button>
                    </td>` : '';
    
                html += `
                    <tr>
                        <td>${report.id}</td>
                        <td>${report.asset_number || ''}</td>
                        <td>${report.asset_name}</td>
                        <td>${report.category_main || '未分类'}</td>
                        <td>${report.category_sub || ''}</td>
                        <td>${report.unit || ''}</td>
                        <td>${report.value || 0}</td>
                        <td><span class="status-badge ${statusClass}">${report.status || '正常'}</span></td>
                        <td>${report.department || '未知部门'}</td>
                        <td>${report.location || ''}</td>
                        <td>${report.purchase_date || ''}</td>
                        <td>${report.description || ''}</td>
                        <td>${imagesHtml}</td>
                        <td>${report.username || ''}</td>
                        <td>${new Date(report.created_at).toLocaleString()}</td>
                        ${actionCell}
                    </tr>
                `;
            });
    
            tableBody.innerHTML = html;
    
            document.querySelectorAll('.delete-report-btn').forEach(btn => {
                btn.addEventListener('click', function () {
                    currentDeleteReportId = this.getAttribute('data-id');
                    deleteReportModal.show();
                });
            });
    
            document.querySelectorAll('.edit-report-btn').forEach(btn => {
                btn.addEventListener('click', function () {
                    currentEditReportId = this.getAttribute('data-id');
                    showEditReportForm(currentEditReportId);
                });
            });
			
			document.querySelectorAll('.duplicate-report-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const reportId = this.getAttribute('data-id');
        duplicateReport(reportId);
    });
});
    
        }
    
	//复制新增
	async function duplicateReport(reportId) {
    try {
        // 获取原始报告数据
        const response = await fetch(`/api/reports/${reportId}`);
        if (!response.ok) throw new Error('获取记录详情失败');
        const originalReport = await response.json();

        // 准备复制数据
        const reportData = {
            asset_number: originalReport.asset_number ? originalReport.asset_number + '_COPY' : '',
            asset_name: originalReport.asset_name,
            category_main: originalReport.category_main,
            category_sub: originalReport.category_sub,
            unit: originalReport.unit,
            value: originalReport.value,
            status: originalReport.status,
            department: originalReport.department,
            location: originalReport.location,
            service_life: originalReport.service_life,
            depreciation_rate: originalReport.depreciation_rate,
            purchase_date: originalReport.purchase_date,
            manufacturer: originalReport.manufacturer,
            model: originalReport.model,
            description: originalReport.description,
            // 注意：图片不复制，因为通常新资产需要新图片
        };

        // 发送创建请求
        const createResponse = await fetch('/api/reports', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(reportData)
        });

        if (!createResponse.ok) {
            const errorData = await createResponse.json();
            throw new Error(errorData.error || '复制新增失败');
        }

        const result = await createResponse.json();
        if (result.success) {
            // 刷新列表
            await loadReports();
            alert('复制新增成功');
        }
    } catch (error) {
        console.error('复制新增失败:', error);
        alert('复制新增失败: ' + error.message);
    }
}
        async function showEditReportForm(reportId) {
            try {
                const response = await fetch(`/api/reports/${reportId}`);
                if (!response.ok) {
                    throw new Error('获取记录详情失败');
                }

                const report = await response.json();

                // 填充表单字段
                document.getElementById('editReportId').value = report.id;
                document.getElementById('editAssetNumber').value = report.asset_number || '';
                document.getElementById('editAssetName').value = report.asset_name || '';
                document.getElementById('editCategoryMain').value = report.category_main || '';
                document.getElementById('editCategorySub').value = report.category_sub || '';
                document.getElementById('editUnit').value = report.unit || '';
                document.getElementById('editValue').value = report.value || '';
                document.getElementById('editStatus').value = report.status || '正常';
                document.getElementById('editDepartment').value = report.department || '';
                document.getElementById('editLocation').value = report.location || '';
                document.getElementById('editServiceLife').value = report.service_life || '';
                document.getElementById('editDepreciationRate').value = report.depreciation_rate || '';
                document.getElementById('editPurchaseDate').value = report.purchase_date || '';
                document.getElementById('editManufacturer').value = report.manufacturer || '';
                document.getElementById('editModel').value = report.model || '';
                document.getElementById('editDescription').value = report.description || '';

                // 处理图片预览和现有图片存储
                const imagePreview = document.getElementById('editImagePreview');
                imagePreview.innerHTML = '';
                const existingImagesInput = document.getElementById('existingImages');

                if (report.images && report.images.length > 0) {
                    // 提取图片文件名（从完整URL中）
                    const imageFilenames = report.images.map(img => {
                        const parts = img.split('/');
                        return parts[parts.length - 1]; // 获取文件名
                    });

                    // 存储现有图片信息
                    existingImagesInput.value = imageFilenames.join(',');

                    // 显示现有图片并添加删除选项
                    report.images.forEach((img, index) => {
                        const imgContainer = document.createElement('div');
                        imgContainer.className = 'position-relative';

                        imgContainer.innerHTML = `
                            <a href="${img}" target="_blank">
                                <img src="${img}" class="asset-image" alt="资产图片">
                            </a>
                            <button type="button" class="btn-close btn-close-white position-absolute top-0 end-0 delete-image-btn" 
                                    data-filename="${imageFilenames[index]}" style="z-index: 10;"></button>
                        `;

                        imagePreview.appendChild(imgContainer);
                    });
                } else {
                    imagePreview.innerHTML = '<span class="text-muted">无图片</span>';
                    existingImagesInput.value = '';
                }

                // 重置新图片预览区域
                document.getElementById('imagePreviewContainer').innerHTML = '';
                document.getElementById('editImages').value = '';

                editReportModal.show();
            } catch (error) {
                console.error('加载编辑表单失败:', error);
                alert('加载编辑表单失败: ' + error.message);
            }
        }

        // 添加新图片预览功能
        document.getElementById('editImages').addEventListener('change', function () {
            const previewContainer = document.getElementById('imagePreviewContainer');
            previewContainer.innerHTML = '';

            if (this.files.length === 0) {
                return;
            }

            if (this.files.length > 3) {
                alert('最多只能上传3张图片');
                this.value = '';
                return;
            }

            for (let i = 0; i < this.files.length; i++) {
                const file = this.files[i];
                const reader = new FileReader();

                reader.onload = function (e) {
                    const imgContainer = document.createElement('div');
                    imgContainer.className = 'position-relative';

                    imgContainer.innerHTML = `
                        <img src="${e.target.result}" class="asset-image" alt="预览图片">
                        <button type="button" class="btn-close btn-close-white position-absolute top-0 end-0 remove-preview-btn" 
                                data-index="${i}" style="z-index: 10;"></button>
                    `;

                    previewContainer.appendChild(imgContainer);
                };

                reader.readAsDataURL(file);
            }

            // 添加删除预览图片的事件监听
            document.querySelectorAll('.remove-preview-btn').forEach(btn => {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    const index = parseInt(this.getAttribute('data-index'));
                    const imgContainer = this.closest('.position-relative');

                    // 从DOM中移除
                    imgContainer.remove();

                    // 从文件列表中移除
                    const dt = new DataTransfer();
                    const files = Array.from(document.getElementById('editImages').files);

                    files.splice(index, 1);
                    files.forEach(file => dt.items.add(file));

                    document.getElementById('editImages').files = dt.files;

                    // 更新预览索引
                    document.querySelectorAll('.remove-preview-btn').forEach((btn, i) => {
                        btn.setAttribute('data-index', i);
                    });
                });
            });
        });

        document.getElementById('saveEditReport').addEventListener('click', async function () {
            const reportId = document.getElementById('editReportId').value;

            // 创建FormData对象
            const formData = new FormData();

            // 添加文本字段
            formData.append('asset_number', document.getElementById('editAssetNumber').value.trim());
            formData.append('asset_name', document.getElementById('editAssetName').value.trim());
            formData.append('category_main', document.getElementById('editCategoryMain').value.trim());
            formData.append('category_sub', document.getElementById('editCategorySub').value.trim());
            formData.append('unit', document.getElementById('editUnit').value.trim());
            formData.append('value', parseFloat(document.getElementById('editValue').value));
            formData.append('status', document.getElementById('editStatus').value);
            formData.append('department', document.getElementById('editDepartment').value.trim());
            formData.append('location', document.getElementById('editLocation').value.trim());
            formData.append('service_life', document.getElementById('editServiceLife').value ?
                parseInt(document.getElementById('editServiceLife').value) : '');
            formData.append('depreciation_rate', document.getElementById('editDepreciationRate').value ?
                parseFloat(document.getElementById('editDepreciationRate').value) : '');
            formData.append('purchase_date', document.getElementById('editPurchaseDate').value);
            formData.append('manufacturer', document.getElementById('editManufacturer').value.trim());
            formData.append('model', document.getElementById('editModel').value.trim());
            formData.append('description', document.getElementById('editDescription').value.trim());

            // 添加现有图片信息
            formData.append('existing_images', document.getElementById('existingImages').value);

            // 添加新上传的图片
            const imageInput = document.getElementById('editImages');
            for (let i = 0; i < imageInput.files.length; i++) {
                formData.append('images', imageInput.files[i]);
            }

            try {
                // 显示加载状态
                this.innerHTML = '<div class="loading-spinner"></div> 保存中...';
                this.disabled = true;

                const response = await fetch(`/api/reports/${reportId}`, {
                    method: 'PUT',
                    body: formData  // 不需要设置Content-Type，浏览器会自动处理
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '更新失败');
                }

                const data = await response.json();
                if (data.success) {
                    await loadReports();
                    editReportModal.hide();
                    alert('记录更新成功');
                }
            } catch (error) {
                console.error('更新失败:', error);
                alert('更新失败: ' + error.message);
            } finally {
                // 恢复按钮状态
                this.innerHTML = '保存修改';
                this.disabled = false;
            }
        });

        // 添加删除现有图片的事件监听（使用事件委托）
        document.getElementById('editImagePreview').addEventListener('click', function (e) {
            if (e.target.classList.contains('delete-image-btn')) {
                e.preventDefault();
                e.stopPropagation();

                const filename = e.target.getAttribute('data-filename');
                const imgContainer = e.target.closest('.position-relative');

                if (confirm('确定要删除这张图片吗？')) {
                    // 从DOM中移除
                    imgContainer.remove();

                    // 更新现有图片列表
                    const existingImagesInput = document.getElementById('existingImages');
                    const currentImages = existingImagesInput.value.split(',');
                    const updatedImages = currentImages.filter(img => img !== filename);
                    existingImagesInput.value = updatedImages.join(',');

                    // 如果没有图片了，显示提示
                    if (updatedImages.length === 0) {
                        document.getElementById('editImagePreview').innerHTML = '<span class="text-muted">无图片</span>';
                    }
                }
            }
        });

        async function deleteReport(reportId) {
            try {
                const response = await fetch(`/api/reports/${reportId}`, {
                    method: 'DELETE'
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '删除失败');
                }

                const data = await response.json();
                if (data.success) {
                    await loadReports();
                    deleteReportModal.hide();
                }
            } catch (error) {
                console.error('删除失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        document.getElementById('confirmDeleteReport').addEventListener('click', function () {
            if (currentDeleteReportId) {
                deleteReport(currentDeleteReportId);
            }
        });

        async function exportToExcel() {
            try {
                const tableBody = document.getElementById('reportsTable');
                const originalContent = tableBody.innerHTML;
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="16" class="text-center py-3">
                            <div class="loading-spinner"></div>
                            <span class="ms-2">导出中...</span>
                        </td>
                    </tr>
                `;

                const startDate = document.getElementById('startDate').value;
                const endDate = document.getElementById('endDate').value;
                const status = document.getElementById('statusFilter').value;
                const department = document.getElementById('departmentFilter').value.trim();

                // 构建导出URL，不包含分页参数
                let url = `/api/reports/export?start_date=${encodeURIComponent(startDate)}&end_date=${encodeURIComponent(endDate)}`;
                if (department) url += `&department=${encodeURIComponent(department)}`;
                if (status !== '全部') url += `&status=${encodeURIComponent(status)}`;

                const response = await fetch(url);
                if (!response.ok) throw new Error('获取数据失败');
                
                // 假设后端返回的是完整的查询结果，而不是分页数据
                const { data: reports } = await response.json();

                if (!reports || reports.length === 0) {
                    throw new Error('没有可导出的数据');
                }

                const excelData = formatReportsForExcel(reports);
                downloadExcelFile(excelData, `资产记录_${new Date().toISOString().slice(0, 10)}.xlsx`);

                tableBody.innerHTML = originalContent;
                alert(`导出成功，共导出 ${reports.length} 条记录`);
            } catch (error) {
                console.error('导出失败:', error);
                document.getElementById('reportsTable').innerHTML = `
                    <tr>
                        <td colspan="16" class="text-center text-danger py-3">导出失败: ${error.message}</td>
                    </tr>
                `;
            }
        }

        function formatReportsForExcel(reports) {
            const headers = [
                'ID', '资产编号', '资产名称', '主分类', '子分类', '单位',
                '价值(元)', '状态', '所属部门', '存放位置', '使用年限',
                '折旧率(%)', '购买日期', '生产厂商', '型号', '详细描述',
                '上报人', '上报时间'
            ];

            const rows = reports.map(report => [
                report.id,
                report.asset_number,
                report.asset_name,
                report.category_main,
                report.category_sub || '无',
                report.unit,
                report.value,
                report.status,
                report.department,
                report.location,
                report.service_life || '无',
                report.depreciation_rate || '无',
                report.purchase_date || '无',
                report.manufacturer || '无',
                report.model || '无',
                report.description || '无',
                report.username,
                new Date(report.created_at).toLocaleString()
            ]);

            return { headers, rows };
        }

        function downloadExcelFile(data, filename) {
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.aoa_to_sheet([data.headers, ...data.rows]);
            XLSX.utils.book_append_sheet(wb, ws, '资产记录');
            XLSX.writeFile(wb, filename);
        }

        function showError(message) {
            const tableBody = document.getElementById('reportsTable');
            tableBody.innerHTML = `
                <tr>
                    <td colspan="16" class="text-center text-danger py-3">${message}</td>
                </tr>
            `;
        }
    </script>
</body>

</html>